package com.action.mvc.auth.service;

import com.action.mvc.auth.dao.RoleDao;
import com.action.mvc.auth.dao.RoleFunctionDao;
import com.action.mvc.auth.entity.Role;
import com.action.mvc.auth.entity.RoleFunction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * Created by Wuxiang on 2017/4/24.
 */
@Service
public class RoleService {
    @Autowired
    RoleDao roleDao;
    @Autowired
    RoleFunctionDao roleFunctionDao;

    /**
     * 保存角色信息，同时保存角色对应的功能
     * @param role
     * @param roleFunctions
     */
    public void addRole(Role role, List<RoleFunction> roleFunctions) {
        roleDao.saveRole(role);
        //将保存的角色对应的id 分别赋给roleFunctions
        roleFunctions.forEach(roleFunction -> roleFunction.setRoleId(role.getId()));
        roleFunctionDao.saveRoleFunctions(roleFunctions);
    }

    /**
     * 修改角色信息，同时修改角色对应的功能
     * @param role
     * @param roleFunctions
     */
    public void editRole(Role role, List<RoleFunction> roleFunctions) {
        roleDao.updateRole(role);
        //先删除原有的对应关系
        roleFunctionDao.deleteByRoleId(role.getId());
        //再保存新的对应关系
        roleFunctions.forEach(roleFunction -> roleFunction.setRoleId(role.getId()));
        roleFunctionDao.saveRoleFunctions(roleFunctions);
    }

    /**
     * 根据角色id删除角色，以及角色所拥有的对应关系
     * @param roleId
     */
    public void deleteRole(Long roleId) {
        roleDao.deleteRoleById(roleId);
        roleFunctionDao.deleteByRoleId(roleId);
    }

    /**
     * 分页查询角色信息
     * @param page
     * @param size
     * @return 角色信息以及所拥有的功能id
     */
    public List<Role> getRoles(int page, int size) {
        List<Role> roles = roleDao.findRolesByPages(page, size);
        roles.forEach(role -> {
            List<RoleFunction> roleFunctions = roleFunctionDao.findRoleFunctionsByRoleId(role.getId());
            StringBuilder functionIds = new StringBuilder();
            roleFunctions.forEach(roleFunction -> {
                functionIds.append(roleFunction.getFunctionId()).append(",");
            });
            if (functionIds.length() > 1) {
                role.setFunctionIds(functionIds.deleteCharAt(functionIds.length()-1).toString());
            }
        });
        return roles;
    }

    /**
     * 根据id集合查询角色信息
     * @param ids
     * @return
     */
    public List<Role> getRoles(Collection<Long> ids){
        return roleDao.findRoleByIds(ids);
    }

    /**
     * 根据用户id 查询角色功能对应关系
     * @param roleId
     * @return
     */
    public List<RoleFunction> getRoleFunctions(Long roleId) {
        return roleFunctionDao.findRoleFunctionsByRoleId(roleId);
    }
}
